What is semver-regex?
The semver-regex npm package provides a regular expression for matching semantic versioning (semver) strings. Semantic versioning is a versioning scheme for software that conveys meaning about the underlying changes. The semver-regex package allows users to easily validate and extract semver strings from text.
What are semver-regex's main functionalities?
Validation of semver strings
This feature allows you to test if a string is a valid semantic version. The code sample demonstrates how to use the semver-regex package to validate a correct semver string ('1.0.0') and an incorrect one ('1.0').
const semverRegex = require('semver-regex');
console.log(semverRegex().test('1.0.0')); // true
console.log(semverRegex().test('1.0')); // false
Extraction of semver strings
This feature allows you to extract a semver string from a larger piece of text. The code sample shows how to use the semver-regex package to find and extract the first semver string from a given text.
const semverRegex = require('semver-regex');
const text = 'The latest version is 3.2.1.';
console.log(text.match(semverRegex())[0]); // '3.2.1'
Other packages similar to semver-regex
semver
The semver package is a more comprehensive tool for working with semantic versions. It not only validates semver strings but also compares them, sorts them, and can increment version numbers according to the semver specification. It offers a richer API compared to the simple regex matching of semver-regex.
compare-versions
The compare-versions package allows you to compare semver strings to determine which is greater, equal, or less. It provides a simple comparison function rather than regex-based validation, focusing on the ordering of versions rather than pattern matching.
semver-regex
Regular expression for matching semver versions
Install
npm install semver-regex
Usage
import semverRegex from 'semver-regex';
semverRegex().test('v1.0.0');
semverRegex().test('1.2.3-alpha.10.beta.0+build.unicorn.rainbow');
semverRegex().exec('unicorn 1.0.0 rainbow')[0];
'unicorn 1.0.0 and rainbow 2.1.3'.match(semverRegex());
Important
If you run the regex against untrusted user input, it's recommended to truncate the string to a sensible length (for example, 50). And if you use this in a server context, you should also give it a timeout.
I do not consider ReDoS a valid vulnerability for this package. It's simply not possible to make it fully ReDoS safe. It's up to the user to set a timeout for the regex if they accept untrusted user input. However, I'm happy to accept pull requests to improve the regex.
Related
- find-versions - Find semver versions in a string
- latest-semver - Get the latest stable semver version from an array of versions
- to-semver - Get an array of valid, sorted, and cleaned semver versions from an array of strings
- semver-diff - Get the diff type of two semver versions:
0.0.1
0.0.2
→ patch
- semver-truncate - Truncate a semver version:
1.2.3
→ 1.2.0